package br.com.iplant.dao;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.com.iplant.util.Conexao;
import br.com.iplant.vo.Talhao;


public class TalhaoDAO {
	
	public String salvar(Talhao talhao) {
		try {

			String sql = "insert into talhoes(area,anoDeAbertura,qtdSacas,fertilidadeSolo,cultura) values (?,?,?,?,?)";
			PreparedStatement ps = Conexao.getCon().prepareStatement(sql);
			
			ps.setDouble(1, talhao.getArea());
			ps.setDate(2,  (Date) talhao.getAnoDeAbertura());
			ps.setInt(3, talhao.getQtdSacas());
			ps.setString(4, talhao.getFertilidadeSolo());
			//ps.set(5, talhao.getCultura());
			
			ps.execute();
			
			System.out.println("Gravado!");
			ps.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ""+talhao;
	}

	public List<Talhao> getTodaosOsTalhoes() {
		List<Talhao> talhoes =new ArrayList<Talhao>();
		try {			
			String sql = "select * from talhoes";
			Statement ps = Conexao.getCon().createStatement();
			ResultSet rs = ps.executeQuery(sql);
			while (rs.next()) {
				talhoes.add(new Talhao(rs.getInt("talhaoId"), rs.getDouble("area"), rs.getDate("anoDeAbertura"), rs.getInt("qtdSacas"), rs.getString("fertilidadeSolo"), null));				
			}			
			ps.close();			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return talhoes;
	}
	
	public Talhao buscarUM(Talhao talhao) {
		try {
			String sql = "select * from talhoes where talhaoId=" + talhao.getTalhaoId() + "";
			Statement ps = Conexao.getCon().createStatement();
			ResultSet rs = ps.executeQuery(sql);
			while (rs.next()) {
				talhao.setTalhaoId(rs.getInt("talhaoId"));
				talhao.setArea(rs.getDouble("area"));
				talhao.setAnoDeAbertura(rs.getDate("anoDeAbertura"));
				talhao.setQtdSacas(rs.getInt("qtdSacas"));
				talhao.setFertilidadeSolo(rs.getString("fertilidadeSolo"));
			}
			
			ps.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return talhao;
	}
}
